public class SearchTree {
    //二叉搜索树
    static class TreeNode{
        public int key;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int key) {
            this.key = key;
        }
    }
    public TreeNode root;
    //插入
    public boolean insert(int key){
        if(root==null){
            root=new TreeNode(key);
            return true;
        }
        TreeNode cur=root;
        TreeNode prev=null;
        while(cur!=null){
            if(cur.key<key){
                prev=cur;
                cur=cur.right;
            }else if(cur.key>key){
                prev=cur;
                cur=cur.left;
            }else{
                return false;
            }
        }
        TreeNode node = new TreeNode(key);
        if(prev.key<key){
            prev.right=node;
        }else{
            prev.left=node;
        }
        return true;
    }
    //查找
    public TreeNode search(int key){
        TreeNode cur=root;
        while(cur!=null){
            if(cur.key==key){
                return cur;
            }else if(cur.key<key){
                cur=cur.right;
            }else{
                cur=cur.left;
            }
        }
        return null;
    }
    //删除
    public boolean remove(int key){
        TreeNode cur=root;
        TreeNode prev=null;
        while(cur!=null){
            if(cur.key<key){
                prev=cur;
                cur=cur.right;
            }else if(cur.key>key){
                prev=cur;
                cur=cur.left;
            }else{
                removeNode(prev,cur);
                return true;
            }
        }
        return false;
    }
    public void removeNode(TreeNode prev,TreeNode cur){
        if(cur.left==null){
            if(cur==root){
                root=cur.right;
            }else if(cur==prev.left){
                prev.left=cur.right;
            }else{
                prev.right=cur.right;
            }
        }else if(cur.right==null){
            if(cur==root){
                root=cur.left;
            }else if(cur==prev.left){
                prev.left=cur.left;
            }else{
                prev.right=cur.left;
            }
        }else{
            TreeNode targetPrev=cur;
            TreeNode target=cur.right;
            //寻找右子树中最小的节点替换删除的节点
            while(target.left!=null){
                targetPrev=target;
                target=target.left;//最小的节点一定在最左侧
            }
            cur.key=target.key;
            //处理删除节点的子树
            if(target==targetPrev.left){
                targetPrev.left=target.right;
            }else{
                targetPrev.right=target.right;
            }
        }
    }
    //中序遍历
    public void inorder(TreeNode root){
        if(root==null) return;
        inorder(root.left);
        System.out.println(root.key+" ");
        inorder(root.right);
    }


}
